<?php

namespace App\Http\Controllers\Platform\Setting;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Resources\Common\DataResource;
use App\Models\Game\Platform\Org\IP;

class IpController extends Controller
{

    /**
     * 获取数据
     */
    public function getData(Request $request)
    {
        $this->validate($request, [
            'plat_code' => 'required|string|max:64'
        ]);
        $platCode = $request->input('plat_code');

        $ips = IP::where('plat_code', $platCode)->get('ip');

        return new DataResource($ips);
    }

    /**
     * 更新或创建数据
     *
     * @param string $platCode
     */
    public function updateOrCreate(Request $request)
    {
        $this->validate($request, [
            'plat_code' => 'required|string|max:64',
            'ips.*.ip' => 'required|ip',
            'ips' => [
                function ($attribute, $items, $fail) {
                    if (count($items) != count(array_unique(array_column($items, 'ip')))) {
                        $fail(trans('validation.unique_value'));
                    }
                }
            ],
        ]);
        $platCode = $request->input('plat_code');
        $ips = $request->input('ips', []);

        // 事物回滚
        IP::dbConnection()->transaction(function () use ($platCode, $ips) {
            // 删除数据
            IP::dbTable()->where('plat_code', $platCode)->delete();
            // 添加数据
            IP::dbTable()->insert(array_map(function ($item) use ($platCode) {
                return $item + ['plat_code' => $platCode, 'in_addr' => inet_pton($item['ip'])];
            }, $ips));
        });

        return new DataResource($ips);
    }

    /**
     * 同步数据
     */
    public function sync(Request $request)
    {
        $data = $request->validate([
            'sourcePlatCode' => 'required|string|max:64',
            'targetPlatCode' => 'required|string|max:64',
            'type' => 'required|in:1,2',
        ]);

        $sourceIps = IP::where('plat_code', $data['sourcePlatCode'])->get('ip')->toArray();
        $targetIps = IP::where('plat_code', $data['targetPlatCode'])->get('ip')->toArray();

        // 1覆盖，2合并
        if ($data['type'] == 2) {
            $ips = collect($targetIps)->merge($sourceIps)->unique('ip')->values()->toArray();
        } else {
            $ips = $sourceIps;
        }

        $platCode = $data['targetPlatCode'];
        // 事物回滚
        IP::dbConnection()->transaction(function () use ($platCode, $ips) {
            // 删除数据
            IP::dbTable()->where('plat_code', $platCode)->delete();
            // 添加数据
            IP::dbTable()->insert(array_map(function ($item) use ($platCode) {
                return $item + ['plat_code' => $platCode, 'in_addr' => inet_pton($item['ip'])];
            }, $ips));
        });

        return new DataResource($ips);
    }
}
